<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CommonQuery
 *
 * @author sethsite
 */
require 'MailControllerClass.php';
require 'MySQLConnectionClass.php';

class CommonQuery {

    //put your code here
    var $dbPrefix;
    var $conn;
    var $con;
    var $database_conn;
    var $fxn;
    var $SITENAME;
    var $currentTotal = 0;
    var $LIMIT_PER;
    var $pageParent;
    var $parentid;
    var $whereWeAreDelimitor = "&raquo; ";
    var $CATEGORY_CAT_TYPE = "cat";
    var $PAGE_CAT_TYPE = "page";
    var $SHARING_OPTION = 139;
    var $ADV_SITE = 139;
    var $FORM_FILE = 21;
    var $banners = array();
    var $where = array();
    var $parentClass;

    function __construct($con, $conn, $db) {
        if (!@session_start()) {
            session_start();
        }
        $this->con = $con;
        $this->conn = $conn;
        $this->database_conn = $db;

        $this->mails = new MailController();
        // $this->fxn = new Utils();
    }

    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {
        if (PHP_VERSION < 6) {
            $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
        }

        $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

        switch ($theType) {
            case "text":
                $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
                break;
            case "long":
            case "int":
                $theValue = ($theValue != "") ? intval($theValue) : "NULL";
                break;
            case "double":
                $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
                break;
            case "date":
                $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
                break;
            case "defined":
                $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
                break;
        }
        return $theValue;
    }

    function getTitleAndContent($offset) {
        if (isset($_GET['page'])) {
            $rs = $this->getContentDetails($_GET['page']);
        } else {
            $rs = $this->getContentDetailsByCat($_GET['cat']);
        }
        $r = mysql_fetch_assoc($rs);

        $msg = "<h1>" . $r["ptitle"] . "</h1>" . getSmallContents2($r["pcontent"], $offset);
        return $msg;
    }

  function processTitle() {
global $page;
        if ((isset($page)&& strlen($page)>1) || isset($_GET['cat']) ) {
            if (strtoupper($page) == "SEARCH") {
                $s = "Search  >> " . $_GET['q'] . " | ";
            } else {
                $s = $this->getPageTitle() . " | ";
            }
        } else {
            $s = "Welcome to  the ";
        }
        return strip_tags($s . $this->SITETITLE);
    }

    function getPageTitle() {
        global $page;
        $param = "content_id";
        if (isset($page)) {
            $value = $page;
        } else if (isset($_GET['cat'])) {
            $value = $_GET['cat'];
            $param = "category_id";
        }

        $q = sprintf("SELECT page_title FROM content WHERE $param = %s", $this->GetSQLValueString($value, "int"));

        $rs = $this->processQueryResult($q);
        $t = "";
        foreach ($rs as $row)
            $t = $row["page_title"];

        return $t;
    }

    function validateForm($ar) {
        $toReturn = true;

        for ($i = 0; $i < count($ar); $i++) {
            if ($_POST[$ar[$i]] == "" || strlen($_POST[$ar[$i]]) < 2) {
                $toReturn = false;
                $str.= $ar[$i];
            }
        }
        echo $str;
        return $toReturn;
    }

    function getContentResource($contentid, $offset, $isAll) {

        $q = "select resource.resource_id, content_id, resource.category_id,category_name,resource_url,resource_description from
        content_resource inner join resource inner join category on
        content_resource.resource_id = resource.resource_id  and resource.category_id = category.category_id
        where content_resource.content_id=$contentid";
        if ($isAll == "no") {
            $q.=" limit 0,30";
        }
        return $this->processQueryResult($q);
    }

    function getConfirmEmail($email, $code) {
        $tor = "no";

        if ($code != "no") {

            $query_gallist = "SELECT *  FROM user_registration where email_address = '$email' and registration_confirmed='$code'";

            mysql_select_db($this->database_conn, $this->conn);
            $rs = mysql_query($query_gallist, $this->conn) or die(mysql_error() . " Error - $linkType " . $query_gallist);
            if (mysql_num_rows($rs) > 0) {
                $q = "update user_registration set registration_confirmed='yes' where email='$email'";
                mysql_select_db($this->database_conn, $this->conn);
                $r = mysql_query($q, $this->conn) or die(mysql_error() . " Error -  " . $q);
                $tor = "yes";
            } else {
                $tor = "no";
            }
        } return $tor;
    }

    function getContentDetails($colname_rs_up) {
        $q = sprintf("SELECT *, date_format(date_created, '%%D %%b, %%Y ::: %%H:%%i%%p') as dateposted , date_format(last_modified, '%%D %%b, %%Y ::: %%H:%%i%%p') as enddate from content  WHERE content_id = %s", $this->GetSQLValueString($colname_rs_up, "int"));
        return $this->processQueryResult($q);
    }

    function getContentOnly($pageId){
       $q=" select category_description from category where category_id =(select category_id from content where content_id=$pageId)";

        $rs = $this->processQueryResult($q);
        foreach($rs as $r)
            return $r;
    }
    function updatePageHits($pg) {
        $q = "update content set page_hits=(page_hits+1) where content_id=" . $pg;
        $this->con->createQuery($q, $this->database_conn);
        //$this->processAllQuery($q);
    }

    function validatePage($pg, $site) {
        $q = "select content_id from content where content_id=" . $pg . " and is_published='yes' and site_id='common' or site_id='$site'";
        $isValid = false;

        $rs = $this->processQueryResult($q);
        if ($rs->getUnlimitedNumberRows() > 0)
            $isValid = true;
        return $isValid;
    }

    function getCategoryDetails($catid) {
        $q = "select * from category inner join content on category.category_id = content.category_id where content.category_id= $catid";
        return $this->processQuery($q);
    }

    function getParentPartners($catid, $cattype) {

        if ($cattype == "cat") {
            $query = "select parent_id, page_title, direct_link from category inner join content on
                 content.category_id = category.category_id
             where category.category_id=$catid";

            $listCat = $this->processQueryResult($query);
            foreach ($listCat as $cat) {
                $parentId = $cat["parent_id"];
            }
            $parentQuery = "select page_title, content.category_id from category inner join content on
                 content.category_id = category.category_id
                 where category.category_id=$parentId";
            $catResult = $this->processQueryResult($parentQuery);
            foreach ($catResult as $catItem) {
                $this->pageParent = $catItem["page_title"];
                $parentId = $catItem["category_id"];
            }
            $query = " select * from category inner join content on
                    content.category_id = category.category_id
             where parent_id = $parentId";
        } else {
            $query = "Select * from content where category_id=$catid  and category_type='$cattype'";
            $queryResult = $this->processQueryResult("select page_title,category_id from content where content_id='$catid'");

            foreach ($queryResult as $catItem) {
                $this->pageParent = $catItem["page_title"];
                $parentId = $catItem["category_id"];
            }
        }
        $parentPatnerList = "";

        //  if($p>14){
        $this->parentid = $parentId;

        $parentListType = $this->getListType($catid);
        $listType = explode(":::", $parentListType);
        $orderBy = $this->processListOrderBy($listType[0]);

        $parentPatnerList = $this->processQueryResult($query . " " . $orderBy . " limit 0 ,15");

        return $parentPatnerList;
    }

    function getCategoryByParent($catid, $limit) {

        $bundleListType = $this->getListType($catid);
        $listType = explode(":::", $bundleListType);
        $orderBy = $this->processListOrderBy($listType[0]);


        $query = sprintf("select content_id,category.category_id,category_name,parent_id,content.page_title,page_content,direct_link,content.date_created,last_modified, date_format(content.date_created, '%%D %%b, %%Y ::: %%H:%%i%%p') as dateposted , date_format(last_modified, '%%D %%b, %%Y ::: %%H:%%i%%p') as enddate from category inner join content on category.category_id = content.category_id where parent_id=%s
                " . $orderBy . " limit %s,%s ",
                        $this->GetSQLValueString($catid, "int"),
                        $this->GetSQLValueString($limit, "int"),
                        $this->GetSQLValueString($this->LIMIT_PER, "int"));

        $categoryList = array();
        $r = $this->processQueryResult($query);
        $cnt = 0;
        $this->currentTotal = $r->getUnlimitedNumberRows();


        foreach ($r as $row) {
            $categoryList[$cnt]["contentid"] = $row["content_id"];
            $categoryList[$cnt]["category"] = $row["category_id"];
            $categoryList[$cnt]["categoryname"] = $row["category_name"];
            $categoryList[$cnt]["parentid"] = $row["parent_id"];
            $categoryList[$cnt]["pcontent"] = $this->fxn->getSmallContents($row["page_content"], 400);
            $categoryList[$cnt]["ptitle"] = $row["page_title"];
            $categoryList[$cnt]["directlink"] = $row["direct_link"];
            $categoryList[$cnt]["picture"] = $this->getFirstImageResource($row["content_id"]);
            $categoryList[$cnt]["startdate"] = $row["dateposted"];
            $categoryList[$cnt]["enddate"] = $row["enddate"];

            $catListType = $this->getListType($row["content_id"]);
            $categoryList[$cnt]["listtype"] = $catListType[0];
            $cnt++;
        }
        return $categoryList;
    }

    function getCategoryOnlyByParent($catid) {
        $q = "select * from category  where parent_id=$catid";
        return $this->processQuery($q);
    }

    //Accepts the pageid and a tag expectiving a list div span or table
    function listContentSmallULPic($pageid) {
        global $HOME_URL;
        $listContent = $this->getContentByCatLimit($pageid, 0, 4);
        if ($listContent->getUnlimitedNumberRows() > 0) {
            $ul = "<ul>";

            $cnt = 0;
            foreach ($listContent as $content) {

                $firstImage = $this->getFirstImageResourceContent($content["content_id"]);
                $cnt++;

                $ul.="<li>";
                $linkURL = $this->fxn->processURL("page", $content["content_id"], $content["page_title"], $content["direct_link"]);
                if (strlen($firstImage) > 0) {
                    $ul.="<a href='" . $linkURL . "'  title='" . $content["page_title"] . "' >";
                    $ul.="<img name='' src='" . $HOME_URL . "resources/image.php?im=" . $firstImage . "&s=250'  alt='" . $content["page_title"] . "' class='imgleft border2' />";
                    $ul.=" </a>";
                }
                $listType= explode(":::", $this->getListType($content["content_id"]));
                // $extraInfo = $this->fxn->pageExtraInfo($content["list_type"],$datecreated,$lastmodified,$type,$src="");
                $ul.=$this->fxn->pageExtraInfo($listType[0], $content["dateposted"], $content["last_modified"], "short");
                $ul.=" <h3><a href='" . $linkURL . "' class='downborder headers'  title='" . $content["page_title"] . "'>";
                $ul.=$content["page_title"] . "</a></h3>";
                $ul.=$this->fxn->getSmallContents($content["page_content"], 150);
                $ul.="<p><a href='" . $linkURL . "' class='readmore'  title='" . $content["page_title"] . "'>Read more...</a></p>";
                $ul.=" </li>";
            }
            $ul.="</ul>";
        }else{$ul="<div class='error'>No Match Found</div>";}
        return $ul;
    }

    //Content Text
    function getContentText($colname_rs_up) {
        $q = sprintf("SELECT page_content from content  WHERE content_id = %s", $this->GetSQLValueString($colname_rs_up, "int"));
        $rs = $this->processQueryResult($q);
        foreach ($rs as $row)
            $rt = $row["page_content"];

        return $rt;
    }

    //ListText
    function listTextUL($pageid) {
        global $HOME_URL;
        $listCatResult = $this->getContentByCatLimit($pageid, 0, 4);

        if ($listCatResult->getUnlimitedNumberRows() > 0) {

            $ul = "<ul>";

            $cnt = 0;
            foreach ($listCatResult as $listItem) {

                $cnt++;

                $eInfo = $this->fxn->pageExtraInfo($listItem["list_type"], $listItem["dateposted"], $listItem["enddate"], "short");
                $ul.="<li> ";
                $link = $this->fxn->processURL("page", $listItem["content_id"], $listItem["page_title"], $listItem["direct_link"]);

                $ul.=" <a href='" . $link . "' class='downborder headers'  title='" . $listItem["page_title"] . "'>";
                $ul.=$eInfo . $listItem["page_title"] . "</a>";
                $ul.=" </li>";
            }
            $ul.="</ul>";
        } else {
            $ul = "<span class='redtxt'>No Match found</span>";
        }
        return $ul;
    }

    //Search Content param search parameter , the offset and where you want to show all or not
    function searchAllContent($val, $offset, $isAll) {
        $query = "select * from content where (content_id like '%$val%' or page_title like '%$val%' or page_content like '%$val%' or category_id like '%$val%') and is_published='yes'  order by last_modified,date_created desc ";

        if ($isAll == "NO")
            $query.=" limit $offset, " . $GLOBALS['NUMTOVIEW'];

        $queryResult = $this->processQueryResult($query);

        $searchResult = array();
        $cnt = 0;

        foreach ($queryResult as $content) {
            $searchResult[$cnt]["title"] = $content["page_title"];
            $searchResult[$cnt]["text"] = $this->getSmallContent($content["page_content"], 300);
            $searchResult[$cnt]["url"] = $this->fxn->processURL("page", $content["content_id"], $content["page_title"], $content["direct_link"]);
            $searchResult[$cnt]["picture"] = $this->getFirstImageResource($content["content_id"]);
            $cnt++;
        }
        return $searchResult;
    }

    function listContentSmallPic($pageid) {
        global $HOME_URL;
        $queryResult = $this->getContentByCatLimit($pageid, 0, 4);
        if ($queryResult->getUnlimitedNumberRows() > 0) {
            $cnt = 0;
            $ul = "<ul>";
            foreach ($queryResult as $content) {
                $cnt++;
                $ul.="";
                $ul.="<li>";
                $firstImage = $this->getFirstImageResourceContent($content["content_id"]);
                $link = $this->fxn->processURL("page", $content["content_id"], $content["page_title"], $content["direct_link"]);
                $ul.="<h4><a href='" . $link . "'  title='" . $content["page_title"] . "' class='downborder'>" . $content["page_title"] . "</a></h4>";
                if (strlen($firstImage) > 0) {
                    $ul.="<a href='" . $link . "'  title='" . $content["page_title"] . "' >";
                    $ul.="<img name='' src='" . $HOME_URL . "resources/image.php?im=" . $firstImage . "&s=80'  alt='" . $content["page_title"] . "' class='imgleft border2' />";
                    $ul.=" </a>";
                }
                $ul.=" <a href='" . $link . "'  title='" . $content["page_title"] . "' class='downborder'>";
                $ul.="</a>";
                $ul.=$this->fxn->getSmallContents($content["page_content"], 100);
                $ul.="<a href='" . $link . "' class='readmore'  title='" . $content["page_title"] . "'> Read more...</a>";
                $ul.=" </li>";
            }
        }
        $ul.="</ul>";
        return $ul;
    }

    function listTitlePic($pageid) {
        global $HOME_URL;
        $queryResult = $this->getContentByCatLimit($pageid, 0, 4);
        if ($queryResult->getUnlimitedNumberRows() > 0) {
            $cnt = 0;
            $ul = "<ul>";
            foreach ($queryResult as $content) {
                $cnt++;
                $ul.="";
                $ul.="<li>";
                $firstImage = $this->getFirstImageResourceContent($content["content_id"]);
                $link = $this->fxn->processURL("page", $content["content_id"], $content["page_title"], $content["direct_link"]);
                if (strlen($firstImage) > 0) {
                    $ul.="<a href='" . $link . "'  title='" . $content["page_title"] . "' >";
                    $ul.="<img name='' src='" . $HOME_URL . "resources/image.php?im=" . $firstImage . "&s=50'  alt='" . $content["page_title"] . "' class='imgleft border2' />";
                    $ul.=" </a>";
                }
                $ul.=" <a href='" . $link . "'  title='" . $content["page_title"] . "' class='downborder'>";
                $ul.="</a>";
                 $listType= explode(":::", $this->getListType($content["content_id"]));
                // $extraInfo = $this->fxn->pageExtraInfo($content["list_type"],$datecreated,$lastmodified,$type,$src="");
                $ul.=$this->fxn->pageExtraInfo($listType[0], $content["dateposted"], $content["last_modified"], "short");
               
                $ul.="<h4><a href='" . $link . "'  title='" . $content["page_title"] . "' class='downborder'>" . $content["page_title"] . "</a></h4><div class=\"clear\"></div>";
                $ul.=" </li>";
            }
        } else {
            return "<div class='info'>No Record</div>";
        }
        $ul.="</ul>";
        return $ul;
    }

    
    function listGallery($pageid,$num) {
        global $HOME_URL;
        $queryResult = $this->getContentByCatLimit($pageid, 0, $num);
        if ($queryResult->getUnlimitedNumberRows() > 0) {
            $cnt = 0;
            $ul = "<ul>";
            foreach ($queryResult as $content) {
                $cnt++;
                $ul.="";
                $ul.="<li>";
                $firstImage = $this->getFirstImageResourceContent($content["content_id"]);
                $link = $this->fxn->processURL("page", $content["content_id"], $content["page_title"], $content["direct_link"]);
                if (strlen($firstImage) > 0) {
                    $ul.="<a href='" . $link . "'  title='" . $content["page_title"] . "' >";
                    $ul.="<img name='' src='" . $HOME_URL . "resources/image.php?im=" . $firstImage . "&s=50'  alt='" . $content["page_title"] . "' class='imgleft border2' />";
                    $ul.=" </a>";
                }
                $ul.=" <a href='" . $link . "'  title='" . $content["page_title"] . "' class='downborder'>";
                $ul.="</a>";
                 $listType= explode(":::", $this->getListType($content["content_id"]));
                // $extraInfo = $this->fxn->pageExtraInfo($content["list_type"],$datecreated,$lastmodified,$type,$src="");
                $ul.=$this->fxn->pageExtraInfo($listType[0], $content["dateposted"], $content["last_modified"], "short");
               
                $ul.="<h4><a href='" . $link . "'  title='" . $content["page_title"] . "' class='downborder'>" . $content["page_title"] . "</a></h4>";
               $ul.="<span class='smaller em'> (" . $this->getResourcesPerPage($content["content_id"], 7) . " Images )</span>";
                $ul.=" <div class='clear'></div></li>";
            }
        } else {
            return "<div class='info'>No Record</div>";
        }
        $ul.="</ul>";
        return $ul;
    }
    function showByGroup($groupid, $type, $order, $rowResult=false) {
        global $HOME_URL;
        $ul = "";
        $query = "select  * from group_member
                left join content
                on group_member.content_id = content.content_id
                where group_member.group_id =" . $groupid . " and group_member_resource is not null order by rand()";


 
        $ul.="<ul id='grp_$groupid'> ";
  
        $queryResult = $this->processQueryResult($query);
    
            if ($rowResult)
            return $queryResult;

        
        foreach ($queryResult as $group) {
                
            if (strlen($group["group_member_resource"]) > 0) {
                echo $group["group_member_resource"]." Group ";
                $imageURL = $this->getResourceDetails($group["group_member_resource"]);
            } else {
                $imageURL = $this->getFirstResourceContent($group["content_id"]);
            }
            if (strlen($group["content_id"]) > 0) {
                $pg = $this->getContentDetails($group["content_id"]);
                foreach ($pg as $content) {
                    $title = $content["page_title"];
                }
                //  $rs =$this->
            } else {
                $title = $group["group_member_title"];
            }
            $cnt++;

            $ul.="<li> ";
          
              if (strlen($group["content_id"]) > 0) {
            $link = $this->fxn->processURL("page", $group["content_id"], $title, $group["group_direct_link"]);
              } else $link=$group["direct_link"]."#";
            if (strlen($imageURL) > 0) {
                $ul.="<a href='" . $link . "'  title='" . $group["resource_description"] . "' >";
                $ul.=$this->fxn->processResources($imageURL, $title); //"<img name='' src='".$HOME_URL."resources/".$imageURL."'  alt='". $group["resource_description"]."' class='imgleft border2' />";
                $ul.=" </a>";
            }

            $ul.=" </li>";
        }
        $ul.="</ul> ";
        return $ul;
    }

    function getFirstResourceContent($contentid) {
        $query = "select category_id,resource_url,resource_description from resource inner join
                content_resource on resource.resource_id = content_resource.resource_id
                where content_id =$contentid  limit 0,1";


        $queryResult = $this->processQueryResult($query);
        $firstImage = "";
        foreach ($queryResult as $resource)
            $firstImage = $resource["resource_url"];

        return $firstImage;
    }

    function listContentWordNumPic($pageid, $cat, $num) {
        global $HOME_URL;
        if ($cat == $this->CATEGORY_CAT_TYPE)
            $queryResult = $this->getCatByCatLimit($pageid, 0, 3);
        else
            $queryResult = $this->getContentByCatLimit($pageid, 0, 3);

        if ($queryResult->getUnlimitedNumberRows() > 0) {
            $ul = "<ul>";


            $cnt = 0;
            foreach ($queryResult as $content) {
                $firstImage = $this->getFirstImageResourceContent($content["contentid"]);
                $cnt++;

                $ul.="<li>";
                $link = $this->fxn->processURL("page", $content["content_id"], $content["page_title"], $content["direct_link"]);
                if (strlen($firstImage) > 0) {
                    $ul.="<a href='" . $link . "'  title='" . $rr["page_title"] . "' >";
                    $ul.="<img name='' src='" . $HOME_URL . "resources/image.php?im=" . $firstImage . "&s=80'  alt='" . $rr["page_title"] . "' class='imgleft border2' />";
                    $ul.=" </a>";
                }
                $ul.=" <a href='" . $link . "'  title='" . $rr["page_title"] . "' class='downborder'>";
                $ul.=$rr["ptitle"] . "</a>";
                $ul.=$this->getSmallContents($content["page_content"], $num);
                $ul.=" <a href='" . $link . "' class='readmore redtxt'  title='" . $rr["page_title"] . "'> Read more...</a>";
                $ul.=" </li>";
            }
        }
        $ul.="</li></ul>";
        return $ul;
    }

    function getSmallContent($param, $wordsNum) {

        $contentTxt = $param;
        $contentTxt = strip_tags($rr);
        if (strlen($contentTxt) < $wordsNum) {
            $str = $contentTxt;
        } else {
            $stringTxt = @strpos($contentTxt, $qs);
            $startFrom = strrpos(substr($rr, 0, $stringTxt), ".");
            //echo  $startFrom." From ".$sttr;
            $startFrom+=1;
            $startFromTxt = substr($contentTxt, $startFrom);
            $dotPos = @strpos($startFromTxt, ".");
            if ($dotPos == 0)
                $dotPos = @strpos($startFromTxt, " ");

            $str = substr($startFromTxt, 0, $dotPos);
            // $str =strip_tags( substr($rr,$startFrom,($sttr-$startFrom+strlen($qs)))) ;
            $str = strip_tags($str);
            //  $str = str_replace($qs,"<span class='highlight'>".$qs."</span>",$str);
            //if(fnmatch($qs."|".strtolower($qs)."|".strtoupper($qs)."|". ucfirst($qs)."|".ucwords($qs),$str))
            //$str = str_replace($qs,"<span class='highlight'>".$qs."</span>",$str);
            // preg_replace((""), $replacement, $subject)
            //$pattern = "'".strtolower($qs)."|".strtoupper($qs)."|".ucfirst($qs)."|".ucwords($qs);
            $searchString = $_GET["q"];
            $pattern = array();
            $pattern[0] = "/" . strtolower($searchString) . "/";
            $pattern[1] = "/" . strtoupper($searchString) . "/";
            $pattern[2] = "/" . ucfirst($searchString) . "/";
            $pattern[3] = "/" . ucwords($searchString) . "/";

            $replacement = array();
            $replacement[0] = "<span class='highlight'>" . strtolower($searchString) . "</span>";
            $replacement[1] = "<span class='highlight'>" . strtoupper($searchString) . "</span>";
            $replacement[2] = "<span class='highlight'>" . ucfirst($searchString) . "</span>";
            $replacement[3] = "<span class='highlight'>" . ucwords($searchString) . "</span>";


            $str = preg_replace($pattern, $replacement, $str);
        }
        if (strlen($str) == 0) {
            if (strlen($r == 0))
                $str = "";
            else
                $str = substr($rr, 0, @strpos($rr, " ", 200));
        }
        return $str;
    }

    function listContentULPic($pageid, $cattype) {
        global $HOME_URL;
        if ($cattype == $this->PAGE_CAT_TYPE) {

            $queryResult = $this->getContentByCatLimit($pageid, 0, 4);
        } else {

            $queryResult = $this->getCatByCatLimit($pageid, 0, 4);
        }
        if ($queryResult->getUnlimitedNumberRows() > 0) {

            $ul = "<ul>";

            $cnt = 0;
            foreach ($queryResult as $content) {


                $firstImage = $this->getFirstImageResourceContent($content["content_id"]);
                $cnt++;

                $ul.="<li> ";
                $link = $this->fxn->processURL("page", $content["content_id"], $content["page_title"], $content["direct_link"]);
                if (strlen($firstImage) > 0) {
                    $ul.="<a href='" . $link . "'  title='" . $content["page_title"] . "' >";
                    $ul.="<img name='' src='" . $HOME_URL . "resources/image.php?im=" . $firstImage . "&s=50'  alt='' class='imgleft border2' />";
                    $ul.=$content["page_title"] . " </a>";
                } else {
                    $ul.="<a href='" . $link . "'  title='" . $content["page_title"] . "' >";
                    $ul.=$content["page_title"] . " </a>";
                }
                $ul.=" </li>";
            }
            $ul.="</ul>";
        }else{ $ul="<div class='error'>No Match Found</div>";}
        return $ul;
    }
    function getFirstResourcePerPageDownload($page,$resourceType,$limit=4){
        
        $listType = $this->getListType($page);
        $requestList = explode(":::", $listType);
        $orderBy = $this->processListTypes($requestList[0]);
        
        $q="select page_title,content.content_id,resource_url from content
inner join content_resource
inner join resource
on content.content_id = content_resource.content_id
and content_resource.resource_id = resource.resource_id
where resource.category_id =$resourceType
and content.category_id =$page and content.category_type='page' $orderBy limit 0,$limit";

        global $HOME_URL;
     $queryResult =$this->processQueryResult($q);
    if ($queryResult->getUnlimitedNumberRows() > 0) {

            $ul = "<ul>";

            $cnt = 0;
            foreach ($queryResult as $content) {
                $cnt++;
                $ul.="<li> ";
                $link = $HOME_URL."resources/download.php?file=".$content["resource_url"];
                $ul.="<a href='" . $link . "'  title='" . $content["page_title"] . "' >";
                $ul.=$content["page_title"];
                $ul.=" </a>";

                $ul.=" </li>";
            }$ul.="</ul>";
        }else{
                $ul="<div class='error'>No Match Found</div>";}

        return $ul;

    }

    function listContentUL($pageid, $cattype, $numtoshow) {

        global $HOME_URL;
        if ($cattype == $this->PAGE_CAT_TYPE) {
            $queryResult = $this->getContentByCatLimit($pageid, 0, $numtoshow);
        } else {

            $queryResult = $this->getCatByCatLimit($pageid, 0, $numtoshow);
        }

        if ($queryResult->getUnlimitedNumberRows() > 0) {

            $ul = "<ul>";

            $cnt = 0;
            foreach ($queryResult as $content) {
                $cnt++;
                $ul.="<li> ";
                $link = $this->fxn->processURL($this->PAGE_CAT_TYPE, $content["content_id"], $content["page_title"], $content["direct_link"]);
                $ul.="<a href='" . $link . "'  title='" . $content["page_title"] . "' >";
                $ul.=$content["page_title"];
                $ul.=" </a>";

                $ul.=" </li>";
            }$ul.="</ul>";
        }else{
                $ul="<div class='error'>No Match Found</div>";}

        return $ul;
    }

//    function getSmallContent($param,$wordsNum) {
//
//        $contentTxt = $param;
//        $contentTxt = strip_tags($rr);
//        if(strlen($contentTxt)<$wordsNum) {
//            $str = $contentTxt;
//        }else {
//            $stringTxt = @strpos($contentTxt,$qs);
//            $startFrom =  strrpos(substr($rr,0,$stringTxt),".");
//            //echo  $startFrom." From ".$sttr;
//            $startFrom+=1;
//            $startFromTxt = substr($contentTxt,$startFrom);
//            $dotPos = @strpos($startFromTxt,".");
//            if($dotPos==0)
//                $dotPos = @strpos($startFromTxt," ");
//
//            $str = substr($startFromTxt,0,$dotPos );
//            // $str =strip_tags( substr($rr,$startFrom,($sttr-$startFrom+strlen($qs)))) ;
//            $str =strip_tags( $str) ;
//            //  $str = str_replace($qs,"<span class='highlight'>".$qs."</span>",$str);
//            //if(fnmatch($qs."|".strtolower($qs)."|".strtoupper($qs)."|". ucfirst($qs)."|".ucwords($qs),$str))
//            //$str = str_replace($qs,"<span class='highlight'>".$qs."</span>",$str);
//            // preg_replace((""), $replacement, $subject)
//            //$pattern = "'".strtolower($qs)."|".strtoupper($qs)."|".ucfirst($qs)."|".ucwords($qs);
//            $searchString= $_GET["q"];
//            $pattern    = array();
//            $pattern[0] = "/".strtolower($searchString)."/";
//            $pattern[1] =  "/".strtoupper($searchString)."/";
//            $pattern[2] =  "/".ucfirst($searchString)."/";
//            $pattern[3] =  "/".ucwords($searchString)."/";
//
//            $replacement    = array();
//            $replacement[0] = "<span class='highlight'>".strtolower($searchString)."</span>";
//            $replacement[1] = "<span class='highlight'>".strtoupper($searchString)."</span>";
//            $replacement[2] = "<span class='highlight'>".ucfirst($searchString)."</span>";
//            $replacement[3] = "<span class='highlight'>".ucwords($searchString)."</span>";
//
//
//            $str = preg_replace($pattern, $replacement, $str);
//        }
//        if(strlen($str)==0) {
//            if(strlen($r==0))
//                $str="";
//            else
//                $str =  substr($rr,0,@strpos($rr," ",200));
//        }
//        return $str;
//    }
//    function getSmallContents($content,$offset) {
//        $rr = strip_tags($content);
//
//        if(strlen($rr)<=$offset) {
//            $str = $rr;
//        }else {
//            $sttr = substr($rr,0,$offset);
//
//            $startFrom = 0;
//            //echo  $startFrom." From ".$sttr;
//            $lastDot = strrpos($sttr,".");
//            $spaceDot = strrpos($sttr," ");
//            if($lastDot>$spaceDot) $to = $lastDot; else $to=$spaceDot;
//
//            $str = substr($sttr,0,$to);
//
//        }if
//
//
//
//        (strlen($str)==0) {
//            if(strlen($r==0))
//                $str="";
//            else
//                $str =  substr($rr,0,@strpos($rr," ",$offset));
//        }
//        return $str;
//    }

    function getFirstImageResourceContent($contentid) {
        $query = "select category_id,resource_url,resource_description from resource inner join
                content_resource on resource.resource_id = content_resource.resource_id
                where content_id =$contentid and resource.category_id=7 limit 0,1";


        $queryResult = $this->processQueryResult($query);
        $firstImage = "";
        foreach ($queryResult as $resource)
            $firstImage = $resource["resource_url"];

        return $firstImage;
    }

    function getFirstImageResource($contentid) {
        $query = "select resource.category_id,resource_url,resource_description from resource inner join
            content_resource on resource.resource_id = content_resource.resource_id
            where content_id =$contentid and resource.category_id = 7 limit 0,1";


        $queryResult = $this->processQueryResult($query);
        $resource = "";$firstImage="";
        foreach ($queryResult as $resource)
            $firstImage = $resource["resource_url"];

        return $firstImage;
    }

    function getContentByCatLimit($catid, $offset, $num) {
        $listType = $this->getListType($catid);
        $requestList = explode(":::", $listType);
        $orderBy = $this->processListTypes($requestList[0]);
        $query = "select * ,date_format(date_created, '%D %b, %Y ::: %H:%i%p') as dateposted , date_format(last_modified, '%D %b, %Y ::: %H:%i%p')as enddate from content where category_id =$catid ";
        $query.=$orderBy;
        $query.=" limit $offset , $num";
      

        return $this->processQueryResult($query);
    }

    function getContentByDates($catid, $dates) {
        $query = "select content_id,page_title,direct_link,category_type,date_created from content where category_id =$catid ";
        $query.=" and date_created like '" . $dates . "%'";
        return $this->processQueryResult($query);
    }

    function getCatByCatLimit($catid, $offset, $num,$ifAll="NO") {
        $listType = $this->getListType($catid);
        $requestList = explode(":::", $listType);
        $orderBy = $this->processListTypes($requestList[0]);

        $query = "select * , date_format(content.date_created, '%%D %%b, %%Y ::: %%H:%%i%%p') as dateposted , date_format(last_modified, '%%D %%b, %%Y ::: %%H:%%i%%p')as enddate from content inner join category on category.category_id=content.category_id where parent_id =$catid ";
        $query.=$orderBy;

        if ($ifAll == "NO")
            $query.=" limit $offset , $num";
        return $this->processQueryResult($query);
    }

    function getPageResourceList($contentid) {
        global $HOME_URL;
        $queryResult = $this->getContentResource($contentid, 0, "yes");
        $t = "<ul>";
        foreach ($queryResult as $resource) {
            $mainImage = @imagecreatefromjpeg($HOME_URL . "resources/" . $resource['resource_url']);
            $mainWidth = @imagesx($mainImage);
            $mainHeight = @imagesy($mainImage);

            $t.="<li><img src='" . $HOME_URL . "resources/" . $resource['resource_url'] . "' /><div class='imgdesc'>" . $resource['resource_description'] . "</div></li>";
        }
        $t.="</ul>";

        echo $t;
    }

    function getResourceDetails($cat) {
        $query = "select resource_url,resource_description from resource
where  resource_id=$cat and category_id=7";

        // echo $q;
        $queryResult = $this->processQueryResult($query);
        $resourceDetails = "";
        foreach ($queryResult as $resource) {
            $resourceDetails = $resource["resource_url"];
        }
        return $resourceDetails;
    }


    function getResourcesPerPage($pageId,$resourceType){
        $query="select count(content_id) as cnt from content_resource inner join resource
        on content_resource.resource_id = resource.resource_id
        where category_id=$resourceType and content_id='$pageId'";
        $queryResult = $this->processQueryResult($query);
  
        $resourceDetails = "";
        foreach ($queryResult as $resource) {
            $resourceDetails = $resource["cnt"];
        }
        return $resourceDetails;

        }
    function getBanner($defaultBanner, $pbanner=0) {
        
       $len = count($this->banners);
     // echo "Len : $pbanner ";
       if (strlen($pbanner) < 1)
      {    
          // echo "BPanner"; 
           $pbanner = 0;
       for($i=0;$i<$len;$i++){
          
           if($this->banners[$i]>0)
           {
               
               $pbanner = $this->banners[$i];
               break;
           }        
       }
       if($pbanner<1){
           $pbanner = $defaultBanner;
           
       }
    }
        
        $bannerImage = $this->getResourceDetails($pbanner);

        
       
        return $bannerImage;
    }

    function processListTypes($listType) {
        $order = "";
        $query = "select category_description from category where category_id=" . $listType;
        $result = $this->processQueryResult($query);
        foreach ($result as $row) {
            return $row["category_description"];
        }
//        switch ($listType) {
//            //News
//            case 2:$order =" order by datecreated  desc ";
//                break;
//            //Events
//            case 3:$order =" and datecreated  >= now() ";
//                break;
//            //Gallery
//            case 4: $order =" order by datecreated  desc ";
//                break;
//            //Quotes
//            case 18:$order =" order by ptitle  asc ";
//                break;
//            //Normal A_Z
//            case 19:	$order =" order by ptitle  asc ";
//                break;
//            //Normal Z - A
//            case 19:	$order =" order by ptitle  desc ";
//                break;
//            //Date Desc
//            case 36:$order =" order by datecreated desc ";
//                break;$this
//            //Date Asc
//            case 37:$order =" order by datecreated asc ";
//                break;
        //}
        //return $order;
    }

    function getListType($categoryid) {
        $query = "select category_id,category_type from content where content_id=$categoryid ";

        $queryResult = $this->processQueryResult($query);
        // echo $query." pnt <br />";
        if ($queryResult->getUnlimitedNumberRows() > 0) {

            foreach ($queryResult as $category) {
                $categoryid = $category["category_id"];
                $cattype = $category["category_type"];
            }
        } else {
            $query = "select category_id,category_type from content where category_id=$categoryid ";
            // echo $query." 1. <br />";
            //   echo $query."  >> 6 <br />";
            $queryResult = $this->processQueryResult($query);
            foreach ($queryResult as $category) {
                $categoryid = $category["category_id"];
                $cattype = $category["category_type"];
            }
        }

        $categoryid = $categoryid;

        if ($cattype != $this->CATEGORY_CAT_TYPE) {

            $query = "select category_id,category_type from content where content_id=$categoryid ";
            //  echo $query."  >> 4 <br />";

            $queryResult = $this->processQueryResult($query);
            if ($queryResult->getUnlimitedNumberRows() > 0) {
                foreach ($queryResult as $content) {
                    $categoryid = $content["category_id"];
                    $cattype = $content["category_type"];
                }
                while ($cattype != $this->CATEGORY_CAT_TYPE) {
                    $query2 = "select category_id, category_type  from content where content_id=$categoryid";

                    $queryResult2 = $this->processQueryResult($query2);

                    foreach ($queryResult2 as $content2) {
                        $categoryid = $content2["category_id"];
                        $cattype = $content2["category_type"];
                    }
                }
            }
        }
        if ($categoryid == null || !isset($categoryid))
            $categoryid = 0;
        //echo $categoryid."- Category ";
        $strQuery = "select list_type,allow_comment from category where category_id=$categoryid";

        $strQueryResult = $this->processQueryResult($strQuery);

        foreach ($strQueryResult as $category)
            $listTypeComment = $category["list_type"] . ":::" . $category["allow_comment"];


        return $listTypeComment;
    }


      function getListTypeName($categoryId) {
        $q = "select category_name from category where category_id=$categoryId";

        $queryResult = $this->processQueryResult($q);
        if ($queryResult->getUnlimitedNumberRows() > 0) {
            foreach ($queryResult as $category) {
                return $category["category_name"];
            }
        }else
            return "";
    }

    function processListOrderBy($listid) {
        $query = "select category_description from category where category_id=" . $listid;

        $queryResult = $this->processQueryResult($query);

        foreach ($queryResult as $category) {
            $listOrder = $category["category_description"];
        }

        return $listOrder;
    }

    function getContentByCat($catid, $offset) {

        $requestListOrder = $this->getListType($catid);

        $listOrder = explode(":::", $requestListOrder);
        $orderBy = $this->processListOrderBy($listOrder[0]);

        //echo $ood."<br />";
        $query = sprintf("select *, date_format(date_created, '%%D %%b, %%Y ::: %%H:%%i%%p') as date_posted , date_format(last_modified, '%%D %%b, %%Y ::: %%H:%%i%%p') as end_date from content where category_id =%s ", $this->GetSQLValueString($catid, "int"));
        $query.=$orderBy;

        $query.=" limit $offset ," . $this->LIMIT_PER;


        $queryResult = $this->processQueryResult($query);
        $this->currentTotal = $queryResult->getUnlimitedNumberRows();
        $cnt = 0;

        $contentList = array();
        foreach ($queryResult as $row) {
            $contentList[$cnt]["contentid"] = $row["content_id"];
            $contentList[$cnt]["parentid"] = $row["category_id"];
            $contentList[$cnt]["pcontent"] = $this->fxn->getSmallContents($row["page_content"], 300);
            $contentList[$cnt]["ptitle"] = $row["page_title"];
            $contentList[$cnt]["directlink"] = $row["direct_link"];
            $contentList[$cnt]["picture"] = $this->getFirstImageResource($row["content_id"]);
            $contentList[$cnt]["fulldate"] = $row["date_created"];
            $contentList[$cnt]["startdate"] = $row["date_posted"];
            $contentList[$cnt]["enddate"] = $row["end_date"];
            $lt = $this->getListType($row["content_id"]);

            $listType = explode(":::", $lt);


            $contentList[$cnt]["listtype"] = $listType[0];
            $cnt++;
        }

        return $contentList;
    }

    function getRSSList($site_id) {
        $q = "select content_id, page_title from content inner join category on category.category_id = content.category_id where is_rss='yes' ";
        $result = $this->processQueryResult($q);
        return $result;
    }

    function createRSSList() {
        $rssResult = $this->getRSSList($_SESSION["SITE_ID"]);
        $element = "<ul>
                    ";
        foreach ($rssResult as $rss) {
            $url = $this->fxn->processURL("rss", $rss["content_id"], $rss["page_title"], "");
            $element.="<li> <a href=\"$url\" title=\"" . $rss["page_title"] . "\">" . $rss["page_title"] . "</a></li>";
        }
        $element.="</ul>";
        return $element;
    }

    function getRelatedPages($contentid) {
        $query = "select * from related_pages where primary_page=" . $contentid . " or secondary_page= " . $contentid;

        $queryResult = $this->processQueryResult($query);
        return $queryResult;
    }

    //This function controls all the urls with in th

    function getRelatedPagesList($contentid) {
        $listRelatedPages = $this->getRelatedPages($contentid);

        $relatePages = array();
        $ct = 0;
        foreach ($listRelatedPages as $relatedPage) {
            $rPage = $relatedPage["primary_page"];
            if ($rPage == $contentid)
                $rPage = $relatedPage["secondary_page"];

            //gettting the page details of the related pages
            $relatedList = $this->getContentDetails($rPage);

            foreach ($relatedList as $related) {
                $relatePages[$ct]["contentid"] = $rPage;
                $relatePages[$ct]["title"] = $related["page_title"];
                $relatePages[$ct]["categoryid"] = $related["category_id"];
                $relatePages[$ct]["url"] = $related["direct_link"];

                $split = $this->getParentNameandId($rPage, $related["category_type"]); //$related["direct_link"];
                $split = explode(":::", $split);
                $relatePages[$ct]["parent"] = $split[1];
            }
            $ct++;
        }
        return $relatePages;
    }

    function whereWeAre($page, $cattype, $curTitle, $curCID, $directlink,$banner) {
        $parentid = $page;
        $cat = $cattype;

        $whereDetails = array();
        $storeArray = array();

        $whereDetails[0][0] = $curCID;
        $whereDetails[0][1] = $curTitle;
        $whereDetails[0][2] = $directlink;
        $whereDetails[0][3] = 0+$banner;
      
        $arrayPointer = 1;

        if ($cat == "page") {
            $w = " content_id = " . $parentid;
        } else {
            $w = " category_id=" . $parentid;
        }
        $catQuery = "select category_type ,content_id ,category_id,page_banner from content where $w";
        //  echo $catQuery;
        $catResult = $this->processQueryResult($catQuery);
        foreach ($catResult as $catR) {
            $cat = $catR["category_type"];
            if ($cat == $this->CATEGORY_CAT_TYPE)
                $parentid = $catR["category_id"];
        }
        //    echo "Page ".$parentid." ".$cat;
        do {
            $storeArray = explode(":::", $this->getParentNameandId($parentid, $cat));
            //    echo "Here  there $arrayPointer.  ".$parentid ."  - $cat<br /> ";
            $tp = $arrayPointer - 1;
            if ($whereDetails[$tp][0] != $storeArray[0]) {
                $whereDetails[$arrayPointer][0] = $storeArray[0];
                $whereDetails[$arrayPointer][1] = $storeArray[1];
                $whereDetails[$arrayPointer][2] = $storeArray[4];
                $whereDetails[$arrayPointer][3] = 0+$storeArray[6];




                $arrayPointer++;
            }
            $cat = $storeArray[3];
            $parentid = $storeArray[2];
            //     echo "$tp Page ".$parentid." $cat <br />";

            unset($storeArray);
        } while ($parentid != $_SESSION["SITE_ID"]);
        // echo "Home <br />";
        global $HOME_URL;

        $cnt = count($whereDetails);
        $counter = 0;
        $locBuilder="";
        for ($i = 3; $i <= $cnt; $i++) {
            $pos = $cnt - $i;
            $locBuilder.= $this->whereWeAreDelimitor . " <a href='" . $this->fxn->processURL($this->PAGE_CAT_TYPE, $whereDetails[$pos][0], $whereDetails[$pos][1], $whereDetails[$pos][2]) . "' title='" . $whereDetails[$pos][1] . "'>" . $whereDetails[$pos][1] . "</a>  ";
            $this->where[$counter] = $whereDetails[$pos][0];
            $this->banners[$counter]=$whereDetails[$pos][3];
   
            if($counter==0)
                $this->parentClass=$this->urlFriendly ( $whereDetails[$pos][1]);
            $counter++;
        }
        $HM = $this->fxn->getHomeLink($HOME_URL, $_SESSION["SITE_NAME"]);
        return "<div class='where'> <a href='$HM' title='Home'>Home</a> " . $locBuilder . "</div>";
        unset($whereDetails);
    }

    function getParentNameandId($id, $cattype) {
        $considered = false;

        if ($cattype == "cat") {
            $q = "select page_title,parent_id,content.category_id,content_id,category_type,direct_link,page_banner from content inner join category
on category.category_id=content.category_id  where content.category_id=" . $id;
//echo "Query :  Cat $considered :".$q."<br />";
            $rs = $this->processQueryResult($q);
            //  echo "Category  inside : $cattype ( $rs->getUnlimitedNumberRows())<br />";
            if ($rs->getUnlimitedNumberRows() > 0) {
                //  echo "Category  inside_ : $cattype <br />";
                $considered = true;
                foreach ($rs as $row) {
                    $store = $row["content_id"] . ":::" . $row["page_title"] . ":::" . $row["parent_id"] . ":::" . $row["category_type"] . ":::" . $row["direct_link"] . ":::" . $row["category_id"]. ":::" . $row["page_banner"];
                }
            }
        }
        if (!$considered) {
            $q = "select page_title,content_id,category_type,direct_link,content.category_id from content where content_id=" . $id;
            //          echo "Query : Page $considered : ".$q."<br />";
            $rs = $this->processQueryResult($q);

            foreach ($rs as $row) {
                $store = $row["content_id"] . ":::" . $row["page_title"] . ":::" . $row["category_id"] . ":::" . $row["category_type"] . ":::" . $row["direct_link"] . $row["category_id"];
                ;
            }
        }
        //    echo $store;
        //  echo $store." - cat - $cattype <br  />";
        return $store;
    }

    function getParentDetails($id, $cattype) {
        $store="";
        if ($cattype == $this->CATEGORY_CAT_TYPE) {
            $query = "select page_title,parent_id,content.category_id,content_id,category_type,direct_link,page_banner from content inner join category
                     on category.category_id=content.category_id  where content.category_id=" . $id;
            $queryResult = $this->processQueryResult($query);

            foreach ($queryResult as $row)
                $store = $row;
        } else {
            $q = "select page_title,content_id,category_type,direct_link,content.category_id , page_banner from content where content_id=" . $id;
            $rs = $this->processQueryResult($q);

            foreach ($rs as $row) {
                $store = $row;
            }
        }
        return $store;
    }

    function siteAds($site_id, $adIndex) {
        $q = "select * from category where category_name like '%advert%' and parent_id=" . $site_id;
        $result = $this->processQueryResult($q);

        foreach ($result as $row) {
            $r = $row["category_id"];
        }

        $adIndex--;
        $q = "select content_id from category inner join content on category.category_id = content.category_id where parent_id = $r  order by category.category_id limit $adIndex,1";

        $result = $this->processQueryResult($q);
        foreach ($result as $row) {
            return $row["content_id"];
        }
    }

    function loadSharingOption() {
        $loadSharingOption = getCategoryByParent($this->SHARING_OPTION);
        //$row= mysql_fetch_assoc($loadSharingOption);

        $ul = "<ul>";
        $where = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] . "&title=" . $this->processTitleOnly();
        for ($i = 0; $i < count($loadSharingOption); $i++) {
            $ul.="<li><a href='" . $loadSharingOption[$i]["directlink"] . $where . "' target='_blank'>" . $loadSharingOption[$i]["categoryname"] . "</a></li";
        }
        $ul . "</ul>";
        echo $ul;
    }

    function getSettings() {
        $q = "select * from setting";
        return $this->processQueryResult($q);
    }

    function getSiteSettings($site) {
        $q = "select * from setting where site_id ='common' or site_id='$site'";
        
        $result = $this->processQueryResult($q);

        return $result;
    }
     function urlFriendly($location, $replaceWith="-") {
        return strtolower($this->replaceSpecialCharacters($location, $replaceWith));
    }

    function replaceSpecialCharacters($location, $replaceWith="-") {
        return (preg_replace("[\W]", $replaceWith, $location));
    }
 function sitePageUrl() {
        global $SITE_ID;
        $pageId=0;
        $parent = $_GET["parent"];
        $parent = $this->urlFriendly($parent, "%");
        $parent.= "%";
        $linkId = $this->getSiteLink($SITE_ID);
        $qParent = " select category_id from category where parent_id=$linkId";
        //echo $qParent;
        $pResult = $this->processQueryResult($qParent);
        $cnt = 0;
        $parentId = "";
        foreach ($pResult as $pRow) {
            if ($cnt > 0)
                $parentId.=" or ";
            $parentId.=" parent_id=" . $pRow["category_id"];

            $cnt++;
//return $siteRow["setting_value"];
        }
        $q = "select parent_id,category.category_id,page_title,content_id from content inner join category on category.category_id =content.category_id
        where page_title like '$parent' and ($parentId )";

        $qr = $this->processQueryResult($q);
        foreach ($qr as $qrow) {
            $pageId = $qrow["content_id"];
        }
        if($pageId<1 ){
            return 0;
        }
$linksArray = array("sub-parent","sub-sub","ss","sss","ssss","sssss");
$linkCnt =count($linksArray);
for($i=0;$i<$linkCnt;$i++){
    $currentUrl = $linksArray[$i];
    if(isset($_GET["$currentUrl"])&& strlen($_GET["$currentUrl"])>1){
              $parent = $this->urlFriendly($_GET["$currentUrl"], "%") . "%";
             $qSP = "select page_title,content_id from content left join category on category.category_id =content.category_id
                    where page_title like '$parent' and ( content.category_id = $pageId or
                    category.parent_id=(select category.category_id from category inner join content
                     on category.category_id=content.category_id where content_id=$pageId) )";

             //echo $qSP;
        $qsp = $this->processQueryResult($qSP);
        foreach ($qsp as $qrows) {
            $pageId = $qrows["content_id"];
        }
      }else return
          $pageId;
        /*$qSP = "select page_title,content_id from content inner join category on category.category_id =content.category_id
                    where page_title like '$parent' and ( category.category_id = $pageId or
                    category.parent_id=(select category.category_id from category inner join content
                     on category.category_id=content.category_id where content_id=$pageId) )";*/
        }

        return $pageId;
    }
    function loadSiteDetails($siteNm) {
        if (isset($_SESSION['SITE_NAME']) && $_SESSION['SITE_NAME'] == $siteNm) {
            $siteId = $_SESSION['SITE_ID'];
            $siteName = $_SESSION['SITE_NAME'];
        } else {
            $siteResult = $this->processQueryResult("select category_id  from category where parent_id = $this->ADV_SITE  and category_name='$siteNm'");
            if (@$siteResult->getUnlimitedNumberRows > 0) {
                foreach ($siteResult as $site) {
                    $siteId = $site["category_id"];
                    $siteName = $siteNm;
                }
            } else {
                $siteId = $this->defaultSite();

                $sR = $this->processQueryResult("select category_name from category where category_id='$siteId'");
                foreach ($sR as $siteRow) {
                    $siteName = $siteRow["category_name"];
                }
            }
        }
        $_SESSION["SITE_NAME"] = $siteName;
        $_SESSION["SITE_ID"] = $siteId;
    }

    function defaultSite() {
        $q = "select * from setting where site_id ='common' AND setting_name='DEFAULT_SITE'";

        $settingResult = $this->processQueryResult($q);
        foreach ($settingResult as $siteRow) {
            return $siteRow["setting_value"];
        }
    }

    function setPageId() {
        global $SITE_ID;
        $paarent = $this->fxn->
                $category = $this->getSiteLink($SITE_ID);
        $q = "select content_id,page_title, content.category_id from
            content.category_id = category.category_id
            where
        ";
    }

    function pageRewriteUrl($page, $cattype, $curTitle, $curCID, $directlink) {
        $parentid = $page;
        $cat = $cattype;

        $whereDetails = array();
        $storeArray = array();

        $whereDetails[0][0] = $curCID;
        $whereDetails[0][1] = $curTitle;
        $whereDetails[0][2] = $directlink;
        $arrayPointer = 1;

        if ($cat == "page") {
            $w = " content_id = " . $parentid;
        } else {
            $w = " category_id=" . $parentid;
        }
        $catQuery = "select category_type ,content_id ,category_id from content where $w";
        //  echo $catQuery;
        $catResult = $this->processQueryResult($catQuery);
        foreach ($catResult as $catR) {
            $cat = $catR["category_type"];
            if ($cat == $this->CATEGORY_CAT_TYPE)
                $parentid = $catR["category_id"];
        }
        //    echo "Page ".$parentid." ".$cat;
        do {
            $storeArray = explode(":::", $this->getParentNameandId($parentid, $cat));
            //    echo "Here  there $arrayPointer.  ".$parentid ."  - $cat<br /> ";
            $tp = $arrayPointer - 1;
            if ($whereDetails[$tp][0] != $storeArray[0]) {
                $whereDetails[$arrayPointer][0] = $storeArray[0];
                $whereDetails[$arrayPointer][1] = $storeArray[1];
                $whereDetails[$arrayPointer][2] = $storeArray[4];




                $arrayPointer++;
            }
            $cat = $storeArray[3];
            $parentid = $storeArray[2];
            //     echo "$tp Page ".$parentid." $cat <br />";

            unset($storeArray);
        } while ($parentid != $_SESSION["SITE_ID"]);
        // echo "Home <br />";
        global $HOME_URL;

        $cnt = count($whereDetails);
        $counter = 0;
        $url = "";
        for ($i = 3; $i <= $cnt; $i++) {
            $pos = $cnt - $i;

//            $locBuilder.= $this->whereWeAreDelimitor . " <a href='" . $this->fxn->processURL($this->PAGE_CAT_TYPE, $whereDetails[$pos][0], $whereDetails[$pos][1], $whereDetails[$pos][2]) . "' title='" . $whereDetails[$pos][1] . "'>" . $whereDetails[$pos][1] . "</a>  ";
//            $this->where[$counter] = $whereDetails[$pos][0];
            $urlFriendly = $this->fxn->urlFriendly($whereDetails[$pos][1]);

            $url.=$urlFriendly . "/";
        }

        //$HM = $this->fxn->getHomeLink($HOME_URL, $_SESSION["SITE_NAME"]);
        //  return "<div class='where'>Where you are <a href='$HM' title='Home'>Home</a> " . $locBuilder . "</div>";
        return $url;
    }

    function processQuery($query) {
        $rs = $this->processQueryResult($query);
        return @mysql_fetch_array($rs);
    }

    function processQueryRow($query) {
        $rs = $this->processQueryResult($query);
        return mysql_fetch_array($rs);
    }

    function processQuery2($query) {
        $rs = $this->processQueryResult($query);
        return ($rs);
    }

    function processAllQuery($q) {
        mysql_select_db($this->database_conn, $this->conn);
        $ras = @mysql_query($q, $this->conn) or die("Error 23: " . $q);
        return $ras;
    }

    function processQueryResult($query) {
        $rs = $this->con->createResultSet($query, $this->database_conn);
        // echo "<br />Un Rows ".$rs->getUnlimitedNumberRows()."<br />";
        // mysql_select_db($this->database_conn,$this->conn);
        //$ras = @mysql_query($query,$this->conn) or die ("Error 23: ".$query.mysql_error());
        //echo $query;
        return $rs;
    }

    function getAllLinks() {
        $strQuery = "select content_id,direct_link,page_title from content inner join category
on category.category_id = content.category_id
where";
        $strQuery.=" category.parent_id =81 or category.parent_id = 12  or category.parent_id = 13 ";

        return $this->processQuery2($strQuery);
    }

    function getWelcomeMessage($siteId) {
        $q = "select page_content from content where category_id=" . $siteId . "";

        $r = $this->processQueryResult($q);
        foreach ($r as $row) {
            $welcome = $row["page_content"];
        }
        return $welcome;
    }

    function getSiteLink($siteId) {
        $q = "select * from category where category_name='Links' and site_id='" . $siteId . "' and parent_id=$siteId  limit 0,1";

        $r = $this->processQueryResult($q);
        foreach ($r as $row) {
            $startPos = $row["category_id"];
        }
        return $startPos;
    }

    function getCategoryList($parentId) {
        $query = "select page_title,content_id, category.category_id,category_name,direct_link,list_type from category inner join content
              on category.category_id = content.category_id  where parent_id=$parentId";
        return $this->processQueryResult($query);
    }

    function getCategoryMembersWithIcons($pageId,$orderType,$start,$end){
        $query="select category_icon,resource_url,resource_description ,category_name,page_title,direct_link,content_id from
                content inner join category inner join resource
                on content.category_id = category.category_id and
                category_icon = resource_id
                where category.parent_id=( select category_id from content where content_id =$pageId)
                $orderType
                limit $start,$end
                ";



        return $this->processQueryResult($query);

    }

    function showIconWithTitle($page,$withTitle=true,$pos="right")
    {
        global $HOME_URL;
        $str="";
        $rU = $this->getCategoryMembersWithIcons($page, " order by rand() ", 0, 1);
        foreach($rU as $r){
            $url = $this->fxn->processURL("page", $r["content_id"], $r["page_title"], $r["direct_link"], "");
            $str.="<div >
                <a href='$url' title='".$r["page_title"]."'>
                <img  src='".$HOME_URL."resources/".$r["resource_url"]."' alt='".$r["resource_description"]."' title='".$r["resource_description"]."' class='$pos'  />
                 ";
            if($withTitle)
                $str.=$r["page_title"];

            $str.=" </a>
            </div>";
        }

        return $str;
    }

    function sitehomeLinks($siteId, $pos, $desc, $showHeading, $shouldDropDown, $withIcon=false,$withHome=false) {
//$siteDetails =  $this->getContentDetails($site_id);

        
        $startPos = $this->getSiteLink($siteId);
        if ($pos > 0) {
            $pos = $pos - 1;
            $qp = "select category_id,list_type from category where parent_id=" . $startPos . " limit $pos , 1";

            $rs1 = $this->processQueryResult($qp);

            foreach ($rs1 as $rowd) {
                $startPos = $rowd["category_id"];
                $listType = $this->processListOrderBy($rowd["list_type"]);
            }
        }

        $query = "select * from category inner join content on category.category_id=content.category_id where parent_id=" . $startPos . " " . $listType;

        $queryResult = $this->processQueryResult($query);
        $linkResult = $this->listItemRowData($queryResult, $pos, $desc, $showHeading, $shouldDropDown, $withIcon,$withHome);

        if ($showHeading == "yes") {
            $linkResult.="<div class='head'>" . $this->getParentCatName($startPos) . "</div>" . $d;
        }

        return $linkResult;
    }

    function homeLinks($pos, $desc, $showHeading, $shouldDropDown) {
        $q = "select * from category where category_name='Home' limit 0,1";
        $r = $this->processQueryResult($q);
        foreach ($r as $row) {
            $startPos = $row["category_id"];
        }

        if ($pos > 0) {
            $pos = $pos - 1;
            $qp = "select * from category where parent_id=" . $startPos . " limit $pos , 1";

            $rs1 = $this->processQueryResult($qp);

            foreach ($rs1 as $rowd) {
                $startPos = $rowd["categoryid"];
                $listType = $this->processListOrderBy($rowd["listtype"]);
            }
        }

        $q_p = "select * from category inner join content on category.category_id=content.category_id where parent_id=" . $startPos . " " . $listType;
        $r_s = $this->processQueryResult($q_p);
        $d = $this->listItemRowData($r_s, $pos, $desc, $showHeading, $shouldDropDown);
        if ($showHeading == "yes") {
            $d = "<div class='head'>" . $this->getParentCatName($startPos) . "</div>" . $d;
        }
        return $d;
    }

    function inWhereList($pageID){
        foreach ($this->where as $key=> $val) {
                if($pageID==$val)
                    return " class='selected ' ";
        }return "  ";
    }

    function inMenuWhereList($pageID){
        foreach ($this->where as $key=> $val) {
                if($pageID==$val)
                    return " class='selected menuitem' ";
        }return "  class='menuitem' ";
    }

    function listItemRowData($rs, $pos, $desc, $showtitle, $shdDrop, $withIcon=false,$withHome=false, $parent="", $subCat=false) {
        global $HOME_URL;
        $rlist = "";
        $HM = $this->fxn->getHomeLink($HOME_URL, $_SESSION["SITE_NAME"]);
        if ($rs->getUnlimitedNumberRows() > 0) {
            $rlist = "<ul>";

            
            if ($pos < 1) {
                
                if($withHome){
                if(count($this->where)<1 && !isset ($_GET["page"]))
                    $homeS=" class='selected menuitem' ";
                else $homeS=" class='menuitem' ";
                $rlist.="<li><a href='$HM' $homeS>Home </a> </li>";
                if ($desc == "yes")
                    $rlist.=" ";}
            }
            foreach ($rs as $row) {
                $icon = "";
                if ($withIcon) {
                    if (strlen($row["category_icon"]) > 0) {
                        $icon = $this->getResourceDetails($row["category_icon"]);
                        if (strlen($icon) > 0)
                            $icon = "<img src=\"" . $HOME_URL . "resources/" . $icon . "\" alt=\"" . strip_tags($row["page_title"]) . "\"  title=\"" . strip_tags($row["page_title"]) . "\" class='icon'/>";
                    }
                }
                $selected = $this->inMenuWhereList($row["content_id"]);
                $rlist.="<li>
                    <a href='" . $this->fxn->processURL("page", $row["content_id"], strip_tags($row["category_name"]), $row["direct_link"]) . "' title='" . strip_tags($row["category_name"]) . "' $selected >" . $icon . $row["category_name"]." ";
                if ($desc == "yes") {
                    $rlist.="<span class='smalltxt'>" . $row["category_description"] . "</span>";
                }
                $rlist.="</a> " ;
                if ($shdDrop == "yes") {

                    $qp = "select category_name,content_id,direct_link,content.category_id from category inner join content on category.category_id=content.category_id where parent_id=" . $row["category_id"] . " ";

                    $r_s = $this->processQueryResult($qp);

                    $rlist.=$this->listItemRowData($r_s, 2, "no", "no", "no");
                }
                $rlist.="</li>";
            }
            $rlist.='</ul>';
        }else
            $rlist = "";$this->getContentDetails(@$pageId);
        return $rlist;
    }

    function getPageForm($contentid) {
        $query = "select * from content_resource inner join resource
             on resource.resource_id  =  content_resource.resource_id   
             where content_id=" . $contentid . " and category_id = " . $this->FORM_FILE;

        $queryResult = $this->processQueryResult($query);
        $forms = "";
        foreach ($queryResult as $resource) {
            $forms.="resources/" . $resource["resource_url"] . ",";
        }
        return $forms;
    }

    function getCountryList() {
        $query = "select name , countrycode from country";
        return $this->processQueryResult($query);
    }

    function showCountryCombo($elementName) {
        $row = $this->getCountryList();
        $store = "";
        foreach ($row as $country) {

            $store.="<$elementName value='" . $country['countrycode'] . "' > " . $country['name'] . "</$elementName>";
        }
        return $store;
    }

    function getCityByCountry($countryCode) {
        $query = "select ID , Name from city where countrycode='$countryCode'";

        return $this->processQueryResult($query);
    }

    function showCityList($elementName, $countryCode) {
        $row = $this->getCityByCountry($countryCode);
        $store = "";
        foreach ($row as $city) {
            $store.="<$elementName value='" . $city['ID'] . "'>" . $city['Name'] . "</$elementName>";
        }
        return $store;
    }

    function registerClient() {
        $str = "Unable to register Client";
        $insertSQL = sprintf("INSERT INTO user_registration (user_name, user_password, site_id) VALUES (%s, %s, %s)",
                        $this->GetSQLValueString($_POST['username'], "text"),
                        $this->GetSQLValueString($_POST['password'], "text"),
                        $this->GetSQLValueString($_POST['site_id'], "text"));
        $this->processAllQuery($insertSQL);
        $user_id = mysql_insert_id();

        $insertSQL = sprintf("INSERT INTO user_detail (user_id,registration_name, country, city, email_address, physical_add, postal_add, contact_person, contact_person_tel, tel_num,site_id) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s,%s, %s)",
                        $this->GetSQLValueString($user_id, "int"),
                        $this->GetSQLValueString($_POST['name'], "text"),
                        $this->GetSQLValueString($_POST['country'], "text"),
                        $this->GetSQLValueString($_POST['city'], "text"),
                        $this->GetSQLValueString($_POST['emailadd'], "text"),
                        $this->GetSQLValueString($_POST['phy_add'], "text"),
                        $this->GetSQLValueString($_POST['postal_add'], "text"),
                        $this->GetSQLValueString($_POST['contact_person'], "text"),
                        $this->GetSQLValueString($_POST['phonenumber'], "text"),
                        $this->GetSQLValueString($_POST['telnum'], "text"),
                        $this->GetSQLValueString($_POST['site_id'], "text"));
        $this->processAllQuery($insertSQL);
        $str = "Client Registration Successful " . $_POST['username'];
        return $str;
    }

    function userComment($page, $startPosition, $numToShow) {
        $commentQuery = "select * from user_comment where content_id=$page
                            and user_comment_response is  null limit $startPosition , $numToShow ";
        $results = $this->processQueryResult($commentQuery);
        return $results;
    }

    function userSubComment($page, $comment) {
        $commentQuery = "select * from user_comment where content_id=$page
                            and user_comment_response=$comment ";
        $results = $this->processQueryResult($commentQuery);

        return $results;
    }

    function userCommentCount($page) {
        $commentQuery = "select count(content_id)as count from user_comment where content_id=$page  and user_comment_response is  null";
        $results = $this->processQueryResult($commentQuery);
        foreach ($results as $row)
            return $row["count"];
    }

    function userAllCommentCount($page) {
        $commentQuery = "select count(content_id)as count from user_comment where content_id=$page ";
        $results = $this->processQueryResult($commentQuery);
        foreach ($results as $row)
            return $row["count"];
    }

	 function productListing($prodList, $limit, $orderBy, $imageSize,$breakOrFloat) {
        if($breakOrFloat=="b")
        {
            $addElement="<br />";
            $imagePos="center";
            $afterEveryThing="";
        }else{
$afterEveryThing="<div class='clear'> </div>";
            $addElement="";
            $imagePos="imgleft";
        }

        $prods = explode(",", $prodList);
        $str = "";
        /*for ($i = 0; $i < count($prods); $i++) {
            if ($i > 0)
                $str.=" or ";
            $str.=" parent_id=" . $prods[$i];
        }
        $q = "select * from content inner join category
            on content.category_id = category.category_id
            where $str
            ";

      
        $rs = $this->processQueryResult($q);
        */$cnt = 0;
        $nq = "";
        
		for ($i = 0; $i < count($prods); $i++) {
            if ($i > 0)
                $str.=" or ";
            $str.=" category_id=" . $prods[$i];
        }
		/*foreach ($rs as $row) {

            if ($cnt > 0)
                $nq.=" or ";
            $nq.=" category_id=" . $row["content_id"];
            $cnt++;
        }*/
        if(strlen($str) >4){
            $str=" where ".$str;

        $oQ = " select * from content $str order by $orderBy  limit 0,$limit ";
//echo $oQ;
       
        $rs1 = $this->processQueryResult($oQ);
        $li = "<ul>";
        global $HOME_URL;
      
        foreach ($rs1 as $ul) {
           
            $firstImage = $this->getFirstImageResource($ul["content_id"]);
            if (strlen($firstImage) > 2)
                $firstImage = "<img class='$imagePos' src='$HOME_URL"."resources/image.php?im=" . $firstImage . "&s=$imageSize' title='" . $ul["page_title"] . "'/>";
            else
                $firstImage="<img  class='$imagePos'  src='$HOME_URL"."resources/image.php?im=images/noimage.jpg&s=$imageSize' title='" . $ul["page_title"] . "'/>";

            $url = $this->fxn->processUrl("page", $ul["content_id"], $ul["page_title"], "");
            $li.="<li class='padding5'>
                        <a href='$url'  title='" . $ul["page_title"] . "'>
                                " . $firstImage .$addElement. $ul["page_title"] . "
                        </a>
                        $afterEveryThing
                  </li>";
        }
        $li.="</ul>".$afterEveryThing;
        }else{
            $li ="No Items Under this category";
        }
        return $li;
    }


}

?>
